package net.hvacapp.cmvrfforandroid.utils;

/**
 * 事务处理
 */
public class TransactionsUtils {

    // 默认操作数量
    private static final int DEFAULT_OPERATION = 1;
    // 操作数
    private int operations;

    private int mSuccessOperation;
    private int mFailOperation;

    // 操作过程监听
    private TransactionListener mTransactionListener;

    public TransactionsUtils() {
        this.operations = DEFAULT_OPERATION;
        this.mSuccessOperation = 0;
        this.mFailOperation = 0;
    }

    public TransactionsUtils(int operations) {
        this.operations = operations;
        this.mSuccessOperation = 0;
        this.mFailOperation = 0;
    }

    /**
     * 设置监听
     *
     * @param transactionListener
     */
    public void setTransactionListener(TransactionListener transactionListener) {
        this.mTransactionListener = transactionListener;
    }

    /**
     * 通知某次操作成功
     */
    public void noticeSuccess() {
        if (mSuccessOperation <= operations) {
            mSuccessOperation++;
        }

        // 判断是否回调
        if (mSuccessOperation + mFailOperation == operations) {
            if (mTransactionListener != null) {
                if (mSuccessOperation == operations) {
                    //成功
                    mTransactionListener.onSuccess(operations);
                } else {
                    mTransactionListener.onFailure(mSuccessOperation, mFailOperation);
                }
            }
        }
    }

    /**
     * 通知某次操作失败
     */
    public void noticeFail() {
        if (mFailOperation <= operations) {
            mSuccessOperation++;
        }

        if (mTransactionListener != null) {
            mTransactionListener.onFailure(mSuccessOperation, mFailOperation);
        }
    }

    /**
     * 重置Transaction
     */
    public void resetTransaction() {
        this.operations = DEFAULT_OPERATION;
        this.mSuccessOperation = 0;
        this.mFailOperation = 0;
    }

    /**
     * 清空已经统计的数目
     */
    public void clearTransaction() {
        this.mSuccessOperation = 0;
        this.mFailOperation = 0;
    }

    /**
     * 返回当前的操作数
     *
     * @return
     */
    public int getOperations() {
        return operations;
    }

    /**
     * 设置当前的操作数
     *
     * @param operations
     */
    public void setOperations(int operations) {
        this.operations = operations;
    }

    public interface TransactionListener {
        /**
         * 成功
         *
         * @param operation 操作次数
         */
        public void onSuccess(int operation);

        /**
         * 失败
         *
         * @param successStat 已经成功的次数
         * @param failStat    已经失败的次数
         */
        public void onFailure(int successStat, int failStat);
    }
}
